package estore;

import java.io.*;
import java.util.*;

public class ProductService4 {
    private final Map<String, Product4> productData = new HashMap<>();
    private String dataFilePath;

    public ProductService4() {
        loadConfig(); // 加载配置
        loadData();   // 加载数据
    }

    // 任务二：加载配置文件
    private void loadConfig() {
        Properties props = new Properties();
        try (InputStreamReader reader = new InputStreamReader(
                new FileInputStream("config.properties"), "UTF-8")) {
            props.load(reader);
            dataFilePath = props.getProperty("data.file.path", "products.dat");
            System.out.println("配置文件加载成功，数据文件路径: " + dataFilePath);
        } catch (FileNotFoundException e) {
            System.out.println("配置文件不存在，使用默认路径: products.dat");
            dataFilePath = "products.dat";
        } catch (IOException e) {
            System.out.println("配置文件读取错误，使用默认路径: products.dat");
            dataFilePath = "products.dat";
        }
    }

    // 任务一：保存数据
    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(dataFilePath))) {
            oos.writeObject(productData);
            System.out.println("商品数据已保存到: " + dataFilePath);
        } catch (IOException e) {
            System.out.println("保存数据失败: " + e.getMessage());
        }
    }

    // 任务一：加载数据
    @SuppressWarnings("unchecked")
    private void loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) {
            System.out.println("数据文件不存在，初始化默认商品数据");
            initializeDefaultProducts();
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(dataFilePath))) {
            Map<String, Product4> loadedData = (Map<String, Product4>) ois.readObject();
            productData.clear();
            productData.putAll(loadedData);
            System.out.println("商品数据已从 " + dataFilePath + " 加载，共 " + productData.size() + " 个商品");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载数据失败，使用默认数据: " + e.getMessage());
            initializeDefaultProducts();
        }
    }

    // 初始化默认商品数据
    private void initializeDefaultProducts() {
        productData.put("p001", new Product4("p001", "Java从入门到精通", 99.0, 100));
        productData.put("p002", new Product4("p002", "高性能MySQL", 128.5, 50));
        productData.put("p003", new Product4("p003", "颈椎康复指南", 45.0, 200));
        productData.put("p004", new Product4("p004", "生发秘籍", 88.0, 0));
    }

    // 其他业务方法保持不变
    public List<Product4> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    public Product4 findProductById(String id) {
        return productData.get(id);
    }

    // 添加商品到库存（可选，用于测试）
    public void addProduct(Product4 product) {
        productData.put(product.getId(), product);
        saveData(); // 自动保存
    }
}